package com.example.e_book.Fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.e_book.Adapter.MyBookAdapter;
import com.example.e_book.DAO.BookDAO;
import com.example.e_book.DAO.BookshelfDAO;
import com.example.e_book.R;
import com.example.e_book.entity.Book;
import com.example.e_book.entity.User;

import java.util.List;

public class MyFragment extends Fragment {

    private TextView tvUsername;
    private Button btnLogout;
    private Button btnRefresh;
    private RecyclerView recyclerViewBooks;
    private MyBookAdapter mybookAdapter;
    private List<Book> bookList;
    private BookDAO bookDAO;
    private BookshelfDAO bookshelfDAO;
    private User user;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_my, container, false);

        // 获取从 MainActivity 传递过来的用户信息
        if (getArguments() != null) {
            user = getArguments().getParcelable("USER");
        }

        tvUsername = view.findViewById(R.id.tvUsername);
        btnLogout = view.findViewById(R.id.btnLogout);
        btnRefresh = view.findViewById(R.id.btnRefresh); // 获取刷新按钮
        recyclerViewBooks = view.findViewById(R.id.recyclerViewBooks2);

        tvUsername.setText("用户名：" + user.getUsername());

        bookDAO = new BookDAO(getContext());
        bookshelfDAO = new BookshelfDAO(getContext(), user);

        bookList = getBooksOnShelf(user.getId());
        mybookAdapter = new MyBookAdapter(bookList, getContext(), user);
        recyclerViewBooks.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerViewBooks.setAdapter(mybookAdapter);

        // 设置刷新按钮的点击事件
        btnRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                refreshBooksOnShelf();
            }
        });

        btnLogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 处理退出登录逻辑
                // 例如，清除用户信息，返回登录界面等
            }
        });

        return view;
    }

    @SuppressLint("NotifyDataSetChanged")
    private void refreshBooksOnShelf() {
        bookList = getBooksOnShelf(user.getId()); // 重新获取书架数据
        mybookAdapter.updateList(bookList); // 更新适配器数据
        mybookAdapter.notifyDataSetChanged(); // 通知数据变化
    }

    private List<Book> getBooksOnShelf(int userId) {
        List<Book> books = bookshelfDAO.getBooksByUserShelf(userId);
        return books;
    }
}